package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Resource;
import com.fsd.admin.model.A_Employee;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.ParametersUtil;
import com.google.gson.Gson;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.fsd.core.util.EhcacheUtil;
import com.fsd.admin.model.Sys_SystemDictionary;
import com.fsd.admin.service.Sys_SystemDictionaryService;
import com.fsd.admin.dao.Sys_SystemDictionaryDao;

@Repository("Sys_SystemDictionaryServiceImpl")
public class Sys_SystemDictionaryServiceImpl extends MainServiceImpl<Sys_SystemDictionary, String> implements Sys_SystemDictionaryService{
    
    @Resource(name = "Sys_SystemDictionaryDaoImpl")
	public void setBaseDao(Sys_SystemDictionaryDao Sys_SystemDictionaryDao) {
		super.setBaseDao(Sys_SystemDictionaryDao);
	}
	
	@Resource(name = "Sys_SystemDictionaryDaoImpl")
	private Sys_SystemDictionaryDao objectDao;
	
	private static final Lock lock = new ReentrantLock();

	private String depict = "";
	/**
	 * 根据字典类型Key加载字典列表
	 * @param key
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Sys_SystemDictionary> getObjectListByKey(String key) throws Exception{
		Map<String, List<Sys_SystemDictionary>> mapSysDict = null;
		lock.lock();
		try {
			if (EhcacheUtil.getInstance().get("SysDict") == null){
				List<Sys_SystemDictionary> list = objectDao.queryByHql("from Sys_SystemDictionary e order by e.sort ");
				mapSysDict = new HashMap<String, List<Sys_SystemDictionary>>();
				for (Sys_SystemDictionary obj : list) {
					if (obj.getParentcode().equals("0")){
						if (!mapSysDict.containsKey(obj.getCode()))
							mapSysDict.put(obj.getCode(), new ArrayList<Sys_SystemDictionary>());
					}
				}
				for (String strKey : mapSysDict.keySet()) {
					for (Sys_SystemDictionary obj : list) {
						if (obj.getParentcode().equals(strKey)){
							mapSysDict.get(strKey).add(obj);
						}
					}
				}
				EhcacheUtil.getInstance().put("SysDict", mapSysDict);
			}else{
				mapSysDict = (Map<String, List<Sys_SystemDictionary>>)EhcacheUtil.getInstance().get("SysDict");
			}
		} finally {
			lock.unlock();
		}
		if (mapSysDict != null && mapSysDict.containsKey(key)){
			List<Sys_SystemDictionary> list = mapSysDict.get(key);
			for (int i = 0; i < list.size(); i++) {
				Sys_SystemDictionary sys_systemDictionary = list.get(i);
				sys_systemDictionary.setText(sys_systemDictionary.getName());
				sys_systemDictionary.setLeaf("true");
				list.set(i, sys_systemDictionary);
			}
			return list;
		}else{
			return null;
		}
	}

	/**
	 * 加载字典类型分页列表
	 * @param param
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public ParametersUtil getDictionaryTypePageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("parentcode", "0"));
		c.addOrder(Order.desc("name"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("name", "%" + objectMap.get("name") + "%"));
			}
		}
		return objectDao.findPager(param, c);
	}

	/**
	 * 加载字典分页列表
	 * @param param
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@Override
	public ParametersUtil getDictionaryPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.addOrder(Order.desc("name"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("code") != null && !"".equals(objectMap.get("code"))){
				c.add(Restrictions.eq("parentcode", objectMap.get("code").toString()));
			}
		}
		return objectDao.findPager(param, c);
	}

	/**
	 * 编辑字典类型
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
	@Override
	public void saveDictionaryType(Sys_SystemDictionary obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Sys_SystemDictionary old_obj = objectDao.get(obj.getId());
			if(!old_obj.getCode().equals(obj.getCode())){
				String sql1 = "select * from Sys_systemdictionary where code = ?";
				List<Sys_SystemDictionary> list = objectDao.queryBySql1(sql1, obj.getCode());
				if(list != null && list.size() > 0){
					throw new BusinessException("字典编码已存在");
				}
				// code发生变化
				String sql = "update Sys_systemdictionary set code = ? where code = ?";
				objectDao.executeSql(sql, obj.getCode(), old_obj.getCode());
			}
			old_obj.setCode(obj.getCode());
			old_obj.setParentcode("0");
			old_obj.setName(obj.getName());
			old_obj.setSymbol(obj.getSymbol());
			old_obj.setSort(0L);
			old_obj.setRemark(obj.getRemark());
			objectDao.update(old_obj);
		}else{
			//添加
			String sql = "select * from Sys_systemdictionary where code = ?";
			List<Sys_SystemDictionary> list = objectDao.queryBySql1(sql, obj.getCode());
			if(list != null && list.size() > 0){
				throw new BusinessException("字典编码已存在");
			}
			//设置主键
			obj.setId(this.getUUID());
			obj.setParentcode("0");
			obj.setSort(0L);
			objectDao.save(obj);
		}
	}

	/**
	 * 编辑字典
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
	@Override
	public void saveDictionary(Sys_SystemDictionary obj, A_Employee employee) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			Sys_SystemDictionary old_obj = objectDao.get(obj.getId());
			if(!old_obj.getCode().equals(obj.getCode())){
				String sql1 = "select * from Sys_systemdictionary where code = ?";
				List<Sys_SystemDictionary> list = objectDao.queryBySql1(sql1, obj.getCode());
				if(list != null && list.size() > 0){
					throw new BusinessException("字典编码已存在");
				}
				// code发生变化
				String sql = "update Sys_systemdictionary set code = ? where code = ?";
				objectDao.executeSql(sql, obj.getCode(), old_obj.getCode());
			}
			old_obj.setCode(obj.getCode());
			old_obj.setParentcode(obj.getParentcode());
			old_obj.setName(obj.getName());
			old_obj.setSymbol(obj.getSymbol());
			old_obj.setSort(obj.getSort());
			old_obj.setRemark(obj.getRemark());
			objectDao.update(old_obj);
		}else{
			//添加
			String sql = "select * from Sys_systemdictionary where code = ?";
			List<Sys_SystemDictionary> list = objectDao.queryBySql1(sql, obj.getCode());
			if(list != null && list.size() > 0){
				throw new BusinessException("字典编码已存在");
			}
			//设置主键
			obj.setId(this.getUUID());
			objectDao.save(obj);
		}
	}

	/**
	 * 删除字典类型
	 * @param parameters
	 * @throws Exception
	 */
	@Override
	public void delDictionaryType(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		for (String id : dir) {
			Sys_SystemDictionary dictionary = objectDao.get(id);
			String sql = "delete from Sys_systemdictionary where parentcode = ?";
			objectDao.executeSql(sql, dictionary.getCode());
			objectDao.delete(dictionary);
		}
	}

	/**
	 * 删除字典
	 * @param parameters
	 * @throws Exception
	 */
	@Override
	public void delDictionary(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		for (String id : dir) {
			Sys_SystemDictionary dictionary = objectDao.get(id);
			objectDao.delete(dictionary);
		}
	}

	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	@Override
	public Sys_SystemDictionary getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		Sys_SystemDictionary obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}
}
